package me.siphone.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import me.siphone.Constants;
import me.siphone.adapter.AnswerAdapter;
import me.siphone.http.api.QueryReplyList;
import me.siphone.http.api.SendSmsApi;
import me.siphone.http.api.StopTTSCallApi;
import me.siphone.http.model.HttpData;
import org.linphone.R;

public class AnswerFragment extends BaseFragment {

    private Button btnStopCall;
    private RecyclerView rvAnswerList;
    private TextView tvUpdateTime;

    private int callType;
    private String callId;
    private String callContent;
    private List<String> callDeviceIds;
    private boolean callHistory;

    private final Timer timer = new Timer();
    private boolean calling = true;
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {

        if (getArguments() != null) {
            callType = getArguments().getInt(Constants.CALL_TYPE);
            callId = getArguments().getString(Constants.CALL_ID);
            callContent = getArguments().getString(Constants.CALL_CONTENT);
            callDeviceIds = getArguments().getStringArrayList(Constants.CALL_DEVICE_IDS);
            callHistory = getArguments().getBoolean(Constants.CALL_HISTORY, false);
        }

        View view = inflater.inflate(R.layout.fragment_answer, container, false);

        TextView tvCallType = view.findViewById(R.id.tv_call_type);
        TextView tvCallContent = view.findViewById(R.id.tv_call_content);
        tvCallType.setText("喊话类型：" + (callType == 0 ? "模版喊话" : "文本喊话"));
        tvCallContent.setText("喊话内容：" + callContent);

        tvUpdateTime = view.findViewById(R.id.tv_update_time);

        rvAnswerList = view.findViewById(R.id.rv_answer_list);
        rvAnswerList.setLayoutManager(new LinearLayoutManager(getContext()));

        btnStopCall = view.findViewById(R.id.btn_stop_call);

        if (callHistory) {
            btnStopCall.setVisibility(View.GONE);
            queryAnswerList(1, 100);
        } else {
            timer.schedule(
                    new TimerTask() {
                        @Override
                        public void run() {
                            queryAnswerList(1, 100);
                        }
                    },
                    0,
                    10000);

            btnStopCall.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (callType == 0) {
                                stopTemplateCall();
                            } else {
                                stopTextCall();
                            }
                        }
                    });
        }

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
        if (calling) {
            if (callType == 0) {
                stopTemplateCall();
            } else {
                stopTextCall();
            }
        }
    }

    private void queryAnswerList(int page, int size) {
        EasyHttp.get(this)
                .api(new QueryReplyList(page, size, callId))
                .request(
                        new HttpCallbackProxy<HttpData<List<QueryReplyList.Reply>>>(this) {
                            @Override
                            public void onHttpSuccess(
                                    @NonNull HttpData<List<QueryReplyList.Reply>> result) {
                                super.onHttpSuccess(result);

                                tvUpdateTime.setText("更新时间：" + sdf.format(new Date()));

                                if (result.getCode() == 200) {
                                    if (rvAnswerList.getAdapter() != null) {
                                        ((AnswerAdapter) rvAnswerList.getAdapter())
                                                .update(result.getRows());
                                    } else {
                                        rvAnswerList.setAdapter(
                                                new AnswerAdapter(result.getRows()));
                                    }
                                }
                            }
                        });
    }

    private void stopTemplateCall() {
        EasyHttp.post(this)
                .api(new SendSmsApi(callDeviceIds, null, 2))
                .request(
                        new HttpCallbackProxy<HttpData<String>>(this) {
                            @Override
                            public void onHttpSuccess(@NonNull HttpData<String> result) {
                                super.onHttpSuccess(result);

                                if (result.getCode() == 200) {
                                    calling = false;
                                    if (getFragmentManager() != null) {
                                        getFragmentManager().popBackStack();
                                    }
                                }
                            }
                        });
    }

    private void stopTextCall() {

        EasyHttp.post(this)
                .api(new StopTTSCallApi(callDeviceIds))
                .request(
                        new HttpCallbackProxy<HttpData<String>>(this) {
                            @Override
                            public void onHttpSuccess(@NonNull HttpData<String> result) {
                                super.onHttpSuccess(result);

                                if (result.getCode() == 200) {
                                    calling = false;
                                    if (getFragmentManager() != null) {
                                        getFragmentManager().popBackStack();
                                    }
                                }
                            }
                        });
    }
}
